// ==UserScript==
// @name         uBlock规则屏蔽器
// @version      3.0
// @description  基于多源规则的内容拦截器，支持自定义订阅，支持本地缓存，支持弹窗拦截，支持页面元素选择，强化移动端广告拦截
// @author       DeepSeek+Cursor
// @icon           https://gitee.com/selling-surprises/Greasyfork-Script-repository/raw/main/%E5%AE%9E%E7%94%A8%E8%84%9A%E6%9C%AC/uBlock%E8%A7%84%E5%88%99%E5%B1%8F%E8%94%BD%E5%99%A8/uBlock-Origin.png
// @match        *://*/*
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_registerMenuCommand
// @connect      *
// @license      MIT
// @updateURL https://gitee.com/selling-surprises/Greasyfork-Script-repository/raw/main/%E5%AE%9E%E7%94%A8%E8%84%9A%E6%9C%AC/uBlock%E8%A7%84%E5%88%99%E5%B1%8F%E8%94%BD%E5%99%A8/uBlock%E8%A7%84%E5%88%99%E5%B1%8F%E8%94%BD%E5%99%A8.user.js
// ==/UserScript==

(function() {
    'use strict';

    // ======================== 规则源配置 ========================
    const DEFAULT_RULE_SOURCES = [
        // 基础广告拦截
        {
            name: 'EasyList 基础规则',
            url: 'https://cdn.jsdelivr.net/gh/uBlockOrigin/uAssetsCDN@main/thirdparties/easylist.txt',
            desc: '国际通用广告过滤核心规则',
            enabled: true
        },
        {
            name: 'AdGuard 中文规则',
            url: 'https://filters.adtidy.org/extension/ublock/filters/224.txt',
            desc: '针对中文互联网环境的广告过滤',
            enabled: true
        },
        
        // 新增谷歌广告专用规则
        {
            name: '谷歌广告专用规则',
            url: 'https://raw.githubusercontent.com/uBlockOrigin/uAssets/master/filters/filters-2023.txt',
            desc: '包含针对谷歌广告和最新广告技术的规则',
            enabled: true
        },
        
        // 隐私保护
        {
            name: 'EasyPrivacy 隐私规则',
            url: 'https://ublockorigin.pages.dev/thirdparties/easyprivacy.txt',
            desc: '拦截跟踪器和隐私收集行为',
            enabled: true
        },
        
        // 安全防护
        {
            name: 'Peter Lowe 广告追踪列表',
            url: 'https://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=1&mimetype=plaintext',
            desc: '知名广告服务器黑名单（曾出现更新问题但已修复）',
            enabled: true
        },
        {
            name: '恶意URL实时拦截',
            url: 'https://malware-filter.gitlab.io/urlhaus-filter/urlhaus-filter-ag-online.txt',
            desc: '基于URLhaus数据库的在线威胁防护',
            enabled: true
        },
        
        // uBlock原生优化
        {
            name: 'uBlock 原生规则',
            url: 'https://ublockorigin.pages.dev/thirdparties/easyprivacy.txt',
            desc: 'uBlock官方优化规则，建议保留',
            enabled: true
        },

        // uBlock filters
        {
            name: "uBlock filters – Ads",
            url: "https://ublockorigin.pages.dev/filters/filters.min.txt",
            desc: "uBlock官方广告规则",
            enabled: true
        },
        {
            name: "uBlock filters – Badware risks",
            url: "https://ublockorigin.pages.dev/filters/badware.min.txt",
            desc: "恶意软件风险防护",
            enabled: true
        },
        {
            name: "uBlock filters – Privacy",
            url: "https://ublockorigin.pages.dev/filters/privacy.min.txt",
            desc: "uBlock官方隐私规则",
            enabled: true
        },
        {
            name: "uBlock filters – Quick fixes",
            url: "https://cdn.jsdelivr.net/gh/uBlockOrigin/uAssetsCDN@main/filters/quick-fixes.min.txt",
            desc: "快速修复规则",
            enabled: true
        },
        {
            name: "uBlock filters – Unbreak",
            url: "https://cdn.jsdelivr.net/gh/uBlockOrigin/uAssetsCDN@main/filters/unbreak.min.txt",
            desc: "破损网站修复规则",
            enabled: true
        },
        
        // 新增 AdGuard 特定规则
        {
            name: "AdGuard 移动广告规则",
            url: "https://filters.adtidy.org/extension/ublock/filters/11.txt",
            desc: "针对移动设备广告的特定规则",
            enabled: true
        },

        // 新增自定义规则源（来自Gitee）
        {
            name: "自定义屏蔽规则",
            url: "https://gitee.com/selling-surprises/ublock-custom-rules/raw/master/Custom-Rules/Rule.js",
            desc: "社区维护的自定义规则",
            enabled: true
        },

        // 新增自定义规则源-手机版（来自Gitee）
        {
            name: "自定义屏蔽规则-手机版",
            url: "https://gitee.com/selling-surprises/ublock-custom-rules/raw/master/Custom-Rules/Rule-Phone.js",
            desc: "社区维护的手机端自定义规则",
            enabled: true
        }
    ];

    // 从存储中获取规则源，如果不存在则使用默认规则源
    let RULE_SOURCES = GM_getValue('customRuleSources', DEFAULT_RULE_SOURCES);

    // 缓存设置
    const DEFAULT_CACHE_CONFIG = {
        enabled: true,
        updateInterval: 60, // 默认更新间隔（分钟）
        lastUpdate: 0
    };
    
    let CACHE_CONFIG = GM_getValue('cacheConfig', DEFAULT_CACHE_CONFIG);

    // 新增：弹窗拦截配置
    const DEFAULT_POPUP_CONFIG = {
        enabled: true,
        threshold: 2  // 短时间内弹窗阈值
    };
    
    let POPUP_CONFIG = GM_getValue('popupConfig', DEFAULT_POPUP_CONFIG);

    // ======================== 核心系统 ========================
    const FILTER_TYPES = {
        NETWORK: 1,     // 网络请求拦截
        COSMETIC: 2,    // 元素隐藏
        SCRIPTLET: 3    // 脚本注入
    };

    let ruleDatabase = {
        networkFilters: new Map(),
        cosmeticFilters: new Map(),
        scriptlets: [],
        bloomFilter: new Set(),
        exceptionRules: new Map(),  // 例外规则
        googleAdSelectors: new Set() // 谷歌广告选择器特化
    };
    
    // 新增缓存系统提升性能
    const regexCache = new Map(); // 正则表达式缓存
    const urlBlockCache = new Map(); // URL拦截结果缓存
    let COMMON_AD_SELECTORS = []; // 常见广告选择器缓存
    
    // 缓存限制配置
    const CACHE_LIMITS = {
        regexCache: 2000,
        urlBlockCache: 5000
    };

    // ======================== 初始化流程 ========================
    (async function init() {
        if (shouldDisable()) return;
        
        try {
            // 添加默认的谷歌广告规则
            addDefaultGoogleAdRules();
            
            // 在DOM内容加载前就开始初始化过滤器
            initializeFilters();
            
            // 检查是否需要从缓存加载或刷新缓存
            const now = Date.now();
            const shouldRefreshCache = !CACHE_CONFIG.lastUpdate || 
                                     (now - CACHE_CONFIG.lastUpdate) > (CACHE_CONFIG.updateInterval * 60 * 1000);
            
            // 检测设备类型，自动处理规则
            const isMobileDevice = detectMobileDevice();
            // 调整规则源状态
            RULE_SOURCES.forEach(source => {
                // 为移动设备启用移动规则，禁用PC规则
                if (source.name === "自定义屏蔽规则" && isMobileDevice) {
                    source.enabled = false;
                }
                // 为PC设备启用PC规则，禁用移动规则
                if (source.name === "自定义屏蔽规则-手机版" && !isMobileDevice) {
                    source.enabled = false;
                }
            });
            // 保存设置
            GM_setValue('customRuleSources', RULE_SOURCES);
            
            // 优先快速应用缓存规则
            if (CACHE_CONFIG.enabled) {
                const startTime = performance.now();
                // 使用非阻塞方式快速加载缓存
                await quickLoadFromCache();
                console.log(`[性能优化] 缓存规则加载完成，耗时: ${(performance.now() - startTime).toFixed(2)}ms`);
                
                // 立即应用过滤功能 - 优先应用拦截
                applyNetworkFiltering();
                applyEarlyFiltering(); // 先应用关键元素过滤
                
                // 延迟应用完整的样式过滤，避免阻塞页面加载
                setTimeout(() => {
                    applyCosmeticFiltering();
                    
                    // 特殊处理谷歌广告
                    applyGoogleAdsFiltering();
                }, 0);
                
                // 如果需要更新缓存，在后台异步进行
                if (shouldRefreshCache) {
                    console.log('[规则更新] 后台更新缓存规则...');
                    setTimeout(async () => {
                        await loadAllRules(true);
                        // 更新最后更新时间
                        CACHE_CONFIG.lastUpdate = Date.now();
                        GM_setValue('cacheConfig', CACHE_CONFIG);
                        // 更新规则后再次应用过滤
                        applyNetworkFiltering();
                        applyCosmeticFiltering();
                        applyGoogleAdsFiltering();
                        console.log('[规则更新] 缓存更新完成');
                    }, 1000);
                }
            } else {
                // 未启用缓存，直接从远程加载
                await loadAllRules(false);
                applyNetworkFiltering();
                applyEarlyFiltering(); // 先应用关键元素过滤
                
                // 延迟应用完整的样式过滤
                setTimeout(() => {
                    applyCosmeticFiltering();
                    applyGoogleAdsFiltering();
                }, 0);
            }
            
            // 注入脚本和设置自动更新
            injectScriptlets();
            blockPopupWindows();
            setupAutoUpdate();
            
            // 添加动态观察器，处理动态添加的元素
            setupMutationObserver();
        } catch (error) {
            console.error('[初始化错误]', error);
        }
    })();

    // 添加默认的谷歌广告规则
    function addDefaultGoogleAdRules() {
        const defaultGoogleAdRules = `
# 谷歌广告通用规则
##.adsbygoogle
##ins.adsbygoogle
##div[id*="google_ads_iframe"]
##div[id*="div-gpt-ad"]
##div[class*="gpt-ad"]
##div[data-ad-client]
##div[data-google-query-id]
##iframe[src*="googleads"]
##iframe[src*="doubleclick"]
##iframe[id*="google_ads_frame"]
##amp-ad[type="adsense"]
##div[data-google-container-id]
##div[id*="banner-ad"]
##div.adunit
##div.GoogleActiveViewElement

# 谷歌广告网络请求
||pagead2.googlesyndication.com^
||googleadservices.com^
||doubleclick.net^
||googlesyndication.com^
||adservice.google.com^
||tpc.googlesyndication.com^
||google-analytics.com/ga.js

# 谷歌广告相关参数
||$xmlhttprequest,domain=~google.com,third-party,redirect-rule=nooptext,match-case,query=adurl
||$xmlhttprequest,domain=~google.com,third-party,redirect-rule=nooptext,match-case,query=gclid
||$xmlhttprequest,domain=~google.com,third-party,redirect-rule=nooptext,match-case,query=adid
||$xmlhttprequest,domain=~google.com,third-party,redirect-rule=nooptext,match-case,query=adclid
`;

        // 获取当前的本地规则
        let localRules = GM_getValue('localCustomRules', '');
        
        // 如果本地规则为空或不包含谷歌广告规则的关键字，添加默认规则
        if (!localRules || 
            (!localRules.includes('googleads') && 
             !localRules.includes('adsbygoogle') && 
             !localRules.includes('doubleclick'))) {
            
            if (localRules && !localRules.endsWith('\n')) {
                localRules += '\n';
            }
            
            localRules += defaultGoogleAdRules;
            GM_setValue('localCustomRules', localRules);
            console.log('[谷歌广告] 已添加默认谷歌广告拦截规则');
        }
    }

    /**
     * 初始化广告拦截和过滤功能
     */
    function initializeFilters() {
        console.log('[初始化] 开始设置过滤器');
        
        // 预定义样式容器
        addStyleContainer();
        
        // 替换原生请求方法
        initializeNetworkInterception();
        
        // 记录初始化完成时间
        window._filterInitTime = Date.now();
        console.log('[初始化] 过滤器设置完成');
    }

    // 检测移动设备函数
    function detectMobileDevice() {
        const userAgent = navigator.userAgent.toLowerCase();
        return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|mobile safari|tablet|ipad|android|android.*mobile|blackberry|iemobile|opera mini/i.test(userAgent) || window.innerWidth <= 768;
    }

    // ======================== 规则加载器 ========================
    // 快速加载缓存规则（优化性能）
    async function quickLoadFromCache() {
        console.log('[规则加载] 快速加载缓存');
        const cachedRules = GM_getValue('cachedRules', {});
        const enabledSources = RULE_SOURCES.filter(source => source.enabled !== false);
        
        // 使用Promise.all加速并行加载
        await Promise.all(enabledSources.map(async (source) => {
            try {
                if (source.isLocal) {
                    // 加载本地规则
                    const localRules = GM_getValue('localCustomRules', '');
                    if (localRules) {
                        parseRules(localRules, source.name);
                    }
                } else if (cachedRules[source.url]) {
                    // 从缓存加载
                    parseRules(cachedRules[source.url].text, source.name);
                }
            } catch (error) {
                console.warn(`[快速加载失败] ${source.name}: ${error.message}`);
            }
        }));
        
        buildBloomFilter();
        optimizeMemoryUsage();
    }
    
    async function loadAllRules(updateCache = false) {
        console.log(`[规则加载] 开始${updateCache ? '并更新缓存' : ''}`);
        // 获取启用的规则源
        const enabledSources = RULE_SOURCES.filter(source => source.enabled !== false);
        
        const loadPromises = enabledSources.map(async (source) => {
            try {
                if (source.isLocal) {
                    // 加载本地规则
                    const localRules = GM_getValue('localCustomRules', '');
                    if (localRules) {
                        parseRules(localRules, source.name);
                        console.log(`[成功加载] ${source.name} (本地)`);
                    }
                } else {
                    // 加载远程规则
                    const text = await fetchWithTimeout(source.url, 10000);
                    parseRules(text, source.name);
                    
                    // 更新缓存
                    if (updateCache) {
                        const cachedRules = GM_getValue('cachedRules', {});
                        cachedRules[source.url] = {
                            text: text,
                            timestamp: Date.now()
                        };
                        GM_setValue('cachedRules', cachedRules);
                    }
                    
                    console.log(`[成功加载] ${source.name}${updateCache ? ' (已缓存)' : ''}`);
                }
            } catch (error) {
                // 如果远程加载失败，尝试从缓存加载
                if (!source.isLocal) {
                    const cachedRules = GM_getValue('cachedRules', {});
                    if (cachedRules[source.url]) {
                        parseRules(cachedRules[source.url].text, source.name);
                        console.log(`[从缓存加载] ${source.name} (远程加载失败)`);
                        return;
                    }
                }
                console.warn(`[加载失败] ${source.name}: ${error.message}`);
            }
        });
        
        await Promise.allSettled(loadPromises);
        buildBloomFilter();
        optimizeMemoryUsage();
    }
    
    // 从缓存加载所有规则
    async function loadFromCache() {
        console.log('[规则加载] 从缓存加载');
        const cachedRules = GM_getValue('cachedRules', {});
        const enabledSources = RULE_SOURCES.filter(source => source.enabled !== false);
        
        enabledSources.forEach(source => {
            try {
                if (source.isLocal) {
                    // 加载本地规则
                    const localRules = GM_getValue('localCustomRules', '');
                    if (localRules) {
                        parseRules(localRules, source.name);
                        console.log(`[成功加载] ${source.name} (本地)`);
                    }
                } else if (cachedRules[source.url]) {
                    // 从缓存加载
                    parseRules(cachedRules[source.url].text, source.name);
                    console.log(`[成功加载] ${source.name} (缓存)`);
                } else {
                    // 没有缓存，需要从远程加载
                    console.log(`[缓存缺失] ${source.name} 尝试远程加载`);
                    fetchWithTimeout(source.url, 10000).then(text => {
                        parseRules(text, source.name);
                        
                        // 更新缓存
                        cachedRules[source.url] = {
                            text: text,
                            timestamp: Date.now()
                        };
                        GM_setValue('cachedRules', cachedRules);
                        
                        console.log(`[成功加载] ${source.name} (已缓存)`);
                    }).catch(error => {
                        console.warn(`[加载失败] ${source.name}: ${error.message}`);
                    });
                }
            } catch (error) {
                console.warn(`[加载失败] ${source.name}: ${error.message}`);
            }
        });
        
        buildBloomFilter();
        optimizeMemoryUsage();
    }

    // ======================== 规则解析引擎 ========================
    function parseRules(rawText, sourceName) {
        const lines = rawText.split(/\r?\n/);
        const batchSize = 300; // 分批处理，减少主线程阻塞
        const batchCount = Math.ceil(lines.length / batchSize);
        
        // 对大型规则集进行批处理
        if (lines.length > batchSize) {
            console.log(`[性能优化] 规则集 ${sourceName} (${lines.length}行) 将分${batchCount}批处理`);
            
            // 立即处理第一批最重要的规则
            processRuleBatch(lines.slice(0, batchSize), sourceName);
            
            // 剩余的规则异步批处理
            let currentBatch = 1;
            const processNextBatch = () => {
                if (currentBatch >= batchCount) return;
                
                const start = currentBatch * batchSize;
                const end = Math.min(start + batchSize, lines.length);
                processRuleBatch(lines.slice(start, end), sourceName);
                
                currentBatch++;
                // 使用requestIdleCallback或setTimeout安排下一批处理
                if (window.requestIdleCallback) {
                    window.requestIdleCallback(() => processNextBatch());
                } else {
                    setTimeout(processNextBatch, 0);
                }
            };
            
            // 开始异步处理
            setTimeout(processNextBatch, 0);
        } else {
            // 小型规则集直接处理
            processRuleBatch(lines, sourceName);
        }
    }
    
    // 批处理规则
    function processRuleBatch(lines, sourceName) {
        lines.forEach(line => {
            line = line.trim();
            if (!line || line.startsWith('!')) return;

            try {
                // 网络拦截规则处理 (||example.com^)
                if (line.startsWith('||')) {
                    const domain = line.match(/\|\|([^\/^]+)/)?.[1];
                    if (domain) {
                        const pattern = convertToRegex(line);
                        addNetworkRule(domain, { pattern, source: sourceName });
                        
                        // 检查谷歌广告特定域名
                        if (isGoogleAdDomain(domain)) {
                            addNetworkRule('googleads', { pattern, source: 'GoogleAds特化规则' });
                        }
                    }
                }
                // 元素隐藏规则 (domain.com##selector)
                else if (line.includes('##')) {
                    const [domains, selector] = line.split('##');
                    if (selector) {
                        const targetDomains = domains ? 
                            domains.split(',').map(d => d.trim()) : 
                            ['global'];
                            
                        targetDomains.forEach(domain => {
                            addCosmeticRule(domain, { 
                                selector, 
                                source: sourceName 
                            });
                        });
                        
                        // 检查是否针对谷歌广告的选择器
                        if (isGoogleAdSelector(selector)) {
                            addCosmeticRule('global', {
                                selector,
                                source: 'GoogleAds特化规则'
                            });
                        }
                    }
                }
                // AdGuard 样式规则 (domain.com#$#style)
                else if (line.includes('#$#')) {
                    const [domains, style] = line.split('#$#');
                    if (style) {
                        const targetDomains = domains ? 
                            domains.split(',').map(d => d.trim()) : 
                            ['global'];
                            
                        targetDomains.forEach(domain => {
                            addCosmeticRule(domain, { 
                                style, 
                                source: sourceName,
                                isStyle: true
                            });
                        });
                    }
                }
                // 特定域名例外规则 (@@||example.com^)
                else if (line.startsWith('@@||')) {
                    const domain = line.match(/@@\|\|([^\/^]+)/)?.[1];
                    if (domain) {
                        const pattern = convertToRegex(line.substring(2)); // 移除@@前缀
                        addExceptionRule(domain, { pattern, source: sourceName });
                    }
                }
                // 脚本注入规则
                else if (line.startsWith('+js') || line.includes('##+js')) {
                    const scriptlet = parseScriptlet(line);
                    scriptlet.source = sourceName;
                    ruleDatabase.scriptlets.push(scriptlet);
                }
            } catch (e) {
                // 忽略解析错误继续处理其他规则
                console.debug(`[规则解析错误] ${line}: ${e.message}`);
            }
        });
    }

    // 添加网络过滤规则
    function addNetworkRule(domain, rule) {
        if (!ruleDatabase.networkFilters.has(domain)) {
            ruleDatabase.networkFilters.set(domain, []);
        }
        ruleDatabase.networkFilters.get(domain).push(rule);
    }

    // 添加例外规则
    function addExceptionRule(domain, rule) {
        if (!ruleDatabase.exceptionRules) {
            ruleDatabase.exceptionRules = new Map();
        }
        
        if (!ruleDatabase.exceptionRules.has(domain)) {
            ruleDatabase.exceptionRules.set(domain, []);
        }
        
        ruleDatabase.exceptionRules.get(domain).push(rule);
    }

    // 添加元素隐藏规则
    function addCosmeticRule(domain, rule) {
        if (!ruleDatabase.cosmeticFilters.has(domain)) {
            ruleDatabase.cosmeticFilters.set(domain, []);
        }
        ruleDatabase.cosmeticFilters.get(domain).push(rule);
        
        // 如果是谷歌广告相关选择器，添加到特殊缓存
        if (isGoogleAdSelector(rule.selector)) {
            if (!ruleDatabase.googleAdSelectors) {
                ruleDatabase.googleAdSelectors = new Set();
            }
            ruleDatabase.googleAdSelectors.add(rule.selector);
        }
    }
    
    // 检查是否是谷歌广告域名
    function isGoogleAdDomain(domain) {
        return /^(.*\.)?google(syndication|adservices|adsyndication|ad|ads|tagservices|tagmanager|doubleclick)\./i.test(domain);
    }
    
    // 检查是否是谷歌广告选择器
    function isGoogleAdSelector(selector) {
        if (!selector) return false;
        
        return selector.includes('gpt-ad') || 
               selector.includes('google_ads') || 
               selector.includes('adsbygoogle') ||
               selector.includes('GoogleAdBlock') ||
               selector.includes('GoogleAd') ||
               selector.includes('adSlot') ||
               selector.includes('ad-slot') ||
               selector.includes('doubleclick');
    }

    // 解析脚本注入规则
    function parseScriptlet(line) {
        // 简单实现，实际应根据格式解析
        const parts = line.split('(');
        return {
            name: parts[0].trim().substring(4), // 移除 '+js(' 前缀
            args: parts[1] ? parts[1].replace(')', '').split(',').map(a => a.trim()) : [],
            code: '', // 实际应解析成对应JS代码
        };
    }

    // ======================== 功能模块 ========================
    // 网络请求拦截（性能优化版）
    function applyNetworkFiltering() {
        // 替换fetch API
        const nativeFetch = window.fetch;
        window.fetch = async function(input) {
            const url = input instanceof Request ? input.url : input;
            
            // 跳过明显的资源文件，提高性能
            if (shouldSkipUrl(url)) {
                return nativeFetch.apply(this, arguments);
            }
            
            // 检查是否应该放行（例外规则）
            if (shouldAllowRequest(url)) {
                return nativeFetch.apply(this, arguments);
            }
            
            // 检查是否应该拦截
            if (shouldBlockRequest(url)) {
                console.log(`[拦截] 阻止请求: ${url}`);
                return fakeResponse();
            }
            
            // 特殊处理谷歌广告URL
            if (isGoogleAdUrl(url)) {
                console.log(`[拦截] 阻止谷歌广告请求: ${url}`);
                return fakeResponse();
            }
            
            return nativeFetch.apply(this, arguments);
        };

        // 替换XMLHttpRequest
        const nativeOpen = XMLHttpRequest.prototype.open;
        XMLHttpRequest.prototype.open = function(method, url) {
            // 跳过明显的资源文件
            if (shouldSkipUrl(url)) {
                return nativeOpen.apply(this, arguments);
            }
            
            // 检查是否应该放行（例外规则）
            if (shouldAllowRequest(url)) {
                return nativeOpen.apply(this, arguments);
            }
            
            // 检查是否应该拦截
            if (shouldBlockRequest(url)) {
                console.log(`[拦截] 阻止XHR请求: ${url}`);
                this.abort();
                return;
            }
            
            // 特殊处理谷歌广告URL
            if (isGoogleAdUrl(url)) {
                console.log(`[拦截] 阻止谷歌广告XHR请求: ${url}`);
                this.abort();
                return;
            }
            
            return nativeOpen.apply(this, arguments);
        };
    }
    
    // 检查请求是否应该放行
    function shouldAllowRequest(url) {
        try {
            const urlObj = new URL(url);
            const hostname = urlObj.hostname;
            
            // 检查例外规则
            if (!ruleDatabase.exceptionRules) return false;
            
            // 检查完整域名匹配
            if (ruleDatabase.exceptionRules.has(hostname)) {
                const rules = ruleDatabase.exceptionRules.get(hostname);
                if (rules.some(r => r.pattern.test(url))) {
                    return true;
                }
            }
            
            // 检查子域名匹配
            for (const [domain, rules] of ruleDatabase.exceptionRules.entries()) {
                if (hostname.endsWith(domain) && rules.some(r => r.pattern.test(url))) {
                    return true;
                }
            }
            
            return false;
        } catch (e) {
            return false;
        }
    }
    
    // 检查是否是谷歌广告URL
    function isGoogleAdUrl(url) {
        try {
            const urlObj = new URL(url);
            const hostname = urlObj.hostname;
            const path = urlObj.pathname;
            
            // 检查域名特征
            if (isGoogleAdDomain(hostname)) {
                return true;
            }
            
            // 检查路径特征
            if (
                path.includes('/ads/') || 
                path.includes('/adsense/') || 
                path.includes('/adsbygoogle') ||
                path.includes('/pagead/') ||
                path.includes('/adservice')
            ) {
                return true;
            }
            
            // 检查查询参数
            if (
                urlObj.search.includes('ad_type=') ||
                urlObj.search.includes('adurl=') ||
                urlObj.search.includes('adunit=')
            ) {
                return true;
            }
            
            return false;
        } catch (e) {
            return false;
        }
    }
    
    // 元素隐藏（支持动态更新）
    function applyCosmeticFiltering() {
        const hostname = location.hostname;
        // 获取全局和当前域名的规则
        const globalRules = ruleDatabase.cosmeticFilters.get('global') || [];
        const domainRules = ruleDatabase.cosmeticFilters.get(hostname) || [];
        
        // 优先处理已加载的元素
        const styleEl = document.getElementById('ublock-cosmetic-filters');
        if (styleEl) {
            const styles = [...globalRules, ...domainRules]
                .map(r => `${r.selector}{display:none!important}`)
                .join('');
            
            styleEl.textContent = styles;
        } else {
            GM_addStyle([...globalRules, ...domainRules]
                .map(r => `${r.selector}{display:none!important}`)
                .join(''));
        }
        
        // 将常见的广告元素选择器缓存起来，用于快速过滤
        COMMON_AD_SELECTORS = [
            ...globalRules.map(r => r.selector), 
            ...domainRules.map(r => r.selector)
        ].filter(selector => 
            selector.includes('ad') || 
            selector.includes('banner') || 
            selector.includes('popup') ||
            selector.includes('float')
        );
    }

    // 提前应用关键过滤规则
    function applyEarlyFiltering() {
        const hostname = location.hostname;
        // 选择高优先级规则：常见广告类选择器
        const globalRules = (ruleDatabase.cosmeticFilters.get('global') || [])
            .filter(r => r.selector.includes('ad') || 
                        r.selector.includes('banner') || 
                        r.selector.includes('popup') ||
                        r.selector.includes('float'));
                        
        const domainRules = (ruleDatabase.cosmeticFilters.get(hostname) || [])
            .filter(r => r.selector.includes('ad') || 
                        r.selector.includes('banner') || 
                        r.selector.includes('popup') ||
                        r.selector.includes('float'));
        
        if (globalRules.length > 0 || domainRules.length > 0) {
            const styles = [...globalRules, ...domainRules]
                .map(r => `${r.selector}{display:none!important}`)
                .join('');
                
            const styleEl = document.getElementById('ublock-early-filters') || document.createElement('style');
            styleEl.id = 'ublock-early-filters';
            styleEl.textContent = styles;
            
            if (!styleEl.parentNode) {
                document.head.appendChild(styleEl);
            }
        }
    }
    
    // 设置DOM变异观察器，处理动态内容
    function setupMutationObserver() {
        // 如果浏览器不支持MutationObserver，直接返回
        if (!window.MutationObserver) return;
        
        // 缓存常见的广告元素选择器
        let COMMON_AD_SELECTORS = [];
        
        // 创建一个节流函数，降低高频处理的性能开销
        const throttle = (func, limit) => {
            let lastFunc;
            let lastRan;
            return function() {
                const context = this;
                const args = arguments;
                if (!lastRan) {
                    func.apply(context, args);
                    lastRan = Date.now();
                } else {
                    clearTimeout(lastFunc);
                    lastFunc = setTimeout(function() {
                        if ((Date.now() - lastRan) >= limit) {
                            func.apply(context, args);
                            lastRan = Date.now();
                        }
                    }, limit - (Date.now() - lastRan));
                }
            };
        };
        
        // 处理新添加的元素
        const processNewNodes = throttle((mutations) => {
            // 过滤出新添加的元素节点
            const addedNodes = [];
            mutations.forEach(mutation => {
                if (mutation.type === 'childList') {
                    mutation.addedNodes.forEach(node => {
                        if (node.nodeType === 1) { // 元素节点
                            addedNodes.push(node);
                        }
                    });
                }
            });
            
            if (addedNodes.length === 0) return;
            
            // 尝试对新元素应用过滤规则
            addedNodes.forEach(node => {
                // 尝试应用常见广告选择器
                COMMON_AD_SELECTORS.forEach(selector => {
                    try {
                        node.querySelectorAll(selector).forEach(el => {
                            el.style.display = 'none';
                        });
                        
                        // 如果节点自身匹配选择器
                        if (node.matches(selector)) {
                            node.style.display = 'none';
                        }
                    } catch (e) {
                        // 忽略无效选择器错误
                    }
                });
            });
        }, 50); // 50毫秒节流
        
        // 创建观察器实例
        const observer = new MutationObserver(processNewNodes);
        
        // 开始观察
        observer.observe(document.documentElement, {
            childList: true,
            subtree: true
        });
        
        // 页面关闭时断开观察器连接
        window.addEventListener('unload', () => {
            observer.disconnect();
        });
    }

    // 注入脚本
    function injectScriptlets() {
        // 注入符合当前域名的脚本
        const hostname = location.hostname;
        const applicableScriptlets = ruleDatabase.scriptlets.filter(s => {
            return s.domains ? s.domains.some(d => hostname.includes(d)) : true;
        });
        
        if (applicableScriptlets.length > 0) {
            const script = document.createElement('script');
            script.textContent = applicableScriptlets.map(s => s.code).join('\n');
            document.head.appendChild(script);
        }
    }

    // 新增：拦截弹出窗口功能
    function blockPopupWindows() {
        // 如果功能未启用，直接返回
        if (!POPUP_CONFIG.enabled) {
            console.log('[拦截弹窗] 功能已禁用');
            return;
        }
        
        // 保存原始的window.open函数
        const originalWindowOpen = window.open;
        
        // 重写window.open函数以拦截弹出窗口
        window.open = function(url, name, specs) {
            // 检查URL是否应该被拦截
            if (url && shouldBlockRequest(url)) {
                console.log(`[拦截弹窗] 已阻止弹出窗口: ${url}`);
                // 返回一个空对象，模拟已打开的窗口
                return {
                    closed: true,
                    document: {},
                    location: {},
                    close: function() {}
                };
            }
            
            // 检查是否为用户交互触发（通常可信的弹窗）
            const isUserAction = (Date.now() - lastInteractionTime) < 1000;
            
            // 如果URL为空或无效，或者是用户交互触发的，允许弹窗
            if (!url || isUserAction) {
                return originalWindowOpen.apply(this, arguments);
            }
            
            // 统计当前页面所有弹窗请求
            popupRequests++;
            
            // 如果短时间内弹窗请求超过阈值，开始拦截
            if (popupRequests > POPUP_CONFIG.threshold) {
                console.log(`[拦截弹窗] 检测到弹窗风暴，已阻止: ${url}`);
                return {
                    closed: true,
                    document: {},
                    location: {},
                    close: function() {}
                };
            }
            
            // 不满足拦截条件，允许弹窗
            return originalWindowOpen.apply(this, arguments);
        };
        
        // 跟踪用户交互
        let lastInteractionTime = 0;
        let popupRequests = 0;
        
        // 监听用户交互事件
        ['click', 'touchstart', 'keydown'].forEach(event => {
            document.addEventListener(event, () => {
                lastInteractionTime = Date.now();
            }, true);
        });
        
        // 每30秒重置弹窗计数器
        setInterval(() => {
            popupRequests = 0;
        }, 30000);
        
        console.log('[拦截弹窗] 弹窗拦截功能已启用');
    }

    // ======================== 工具函数 ========================
    function convertToRegex(filter) {
        // 缓存正则表达式避免重复创建
        if (regexCache.has(filter)) {
            return regexCache.get(filter);
        }
        
        const regex = new RegExp(
            filter
            .replace(/\*/g, '.*')
            .replace(/\^/g, '([\\x00-\\x24\\x26-\\x2C\\x2F\\x3A-\\x40\\x5B-\\x5E\\x60\\x7B-\\x7F]|$)')
            .replace(/\|\|/g, '^https?://([^/]+\\.)?')
        );
        
        regexCache.set(filter, regex);
        return regex;
    }

    function shouldBlockRequest(url) {
        try {
            // 快速检查缓存
            if (urlBlockCache.has(url)) {
                return urlBlockCache.get(url);
            }
            
            const host = new URL(url).hostname;
            // 使用布隆过滤器进行预检查以提高性能
            if (!ruleDatabase.bloomFilter.has(host)) {
                urlBlockCache.set(url, false);
                return false;
            }
            
            // 布隆过滤器命中后，再进行详细检查
            const shouldBlock = ruleDatabase.networkFilters.get(host)?.some(r => r.pattern.test(url)) || false;
            
            // 缓存结果以提高后续检查速度
            urlBlockCache.set(url, shouldBlock);
            return shouldBlock;
        } catch {
            return false;
        }
    }

    // 判断是否应该跳过URL检查（优化性能）
    function shouldSkipUrl(url) {
        try {
            // 跳过常见的基本资源
            if (url.endsWith('.css') || 
                url.endsWith('.png') || 
                url.endsWith('.jpg') || 
                url.endsWith('.svg') ||
                url.endsWith('.woff')) {
                return true;
            }
            
            // 跳过当前域名下的基本资源
            const urlObj = new URL(url);
            if (urlObj.hostname === location.hostname && 
                (urlObj.pathname.endsWith('.js') || urlObj.pathname.includes('/assets/'))) {
                return true;
            }
            
            return false;
        } catch {
            return false;
        }
    }

    // ======================== 新增工具函数 ========================
    async function fetchWithTimeout(url, timeout = 10000) {
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: "GET",
                url: url,
                timeout: timeout,
                onload: (response) => {
                    if (response.status >= 200 && response.status < 300) {
                        resolve(response.responseText);
                    } else {
                        reject(new Error(`HTTP错误 ${response.status}`));
                    }
                },
                onerror: (error) => reject(error),
                ontimeout: () => reject(new Error('请求超时'))
            });
        });
    }

    function buildBloomFilter() {
        ruleDatabase.networkFilters.forEach((rules, domain) => {
            ruleDatabase.bloomFilter.add(domain);
        });
    }

    function optimizeMemoryUsage() {
        // 内存优化策略
        ruleDatabase.networkFilters = new Map([...ruleDatabase.networkFilters.entries()].sort());
        ruleDatabase.cosmeticFilters = new Map([...ruleDatabase.cosmeticFilters.entries()].sort());
        ruleDatabase.scriptlets.sort();
        
        // 清理过大的缓存
        if (regexCache.size > CACHE_LIMITS.regexCache) {
            // 清除多余的缓存条目
            const entriesToRemove = regexCache.size - CACHE_LIMITS.regexCache;
            let count = 0;
            for (const key of regexCache.keys()) {
                regexCache.delete(key);
                count++;
                if (count >= entriesToRemove) break;
            }
            console.log(`[性能优化] 清理了 ${entriesToRemove} 条正则缓存`);
        }
        
        if (urlBlockCache.size > CACHE_LIMITS.urlBlockCache) {
            // 清除多余的URL缓存条目
            const entriesToRemove = urlBlockCache.size - CACHE_LIMITS.urlBlockCache;
            let count = 0;
            for (const key of urlBlockCache.keys()) {
                urlBlockCache.delete(key);
                count++;
                if (count >= entriesToRemove) break;
            }
            console.log(`[性能优化] 清理了 ${entriesToRemove} 条URL缓存`);
        }
    }

    function setupAutoUpdate() {
        // 根据配置设置的时间间隔自动更新规则
        setInterval(async () => {
            console.log('开始自动更新规则...');
            await loadAllRules(true);
            
            // 更新最后更新时间
            CACHE_CONFIG.lastUpdate = Date.now();
            GM_setValue('cacheConfig', CACHE_CONFIG);
        }, CACHE_CONFIG.updateInterval * 60 * 1000);
    }
    
    // 清除所有缓存的规则
    function clearCache() {
        GM_setValue('cachedRules', {});
        CACHE_CONFIG.lastUpdate = 0;
        GM_setValue('cacheConfig', CACHE_CONFIG);
        console.log('[缓存清理] 所有缓存规则已清除');
        return true;
    }

    // ======================== 订阅管理功能 ========================
    function addCustomSubscription(name, url, desc = "") {
        // 检查是否已存在相同URL的订阅
        const existingIndex = RULE_SOURCES.findIndex(source => source.url === url);
        
        if (existingIndex !== -1) {
            // 已存在，更新信息
            RULE_SOURCES[existingIndex] = {
                name: name,
                url: url,
                desc: desc,
                enabled: true
            };
        } else {
            // 添加新订阅
            RULE_SOURCES.push({
                name: name,
                url: url,
                desc: desc,
                enabled: true
            });
        }
        
        // 保存到存储
        GM_setValue('customRuleSources', RULE_SOURCES);
        
        // 重新加载规则
        ruleDatabase = {
            networkFilters: new Map(),
            cosmeticFilters: new Map(),
            scriptlets: [],
            bloomFilter: new Set()
        };
        
        loadAllRules();
        return true;
    }

    // 添加本地自定义规则
    function addLocalCustomRules(rules, name = "本地自定义规则") {
        // 将规则文本直接保存到存储
        GM_setValue('localCustomRules', rules);
        
        // 检查是否已存在本地规则源
        const existingIndex = RULE_SOURCES.findIndex(source => source.isLocal === true);
        
        if (existingIndex !== -1) {
            // 更新现有的本地规则
            RULE_SOURCES[existingIndex].name = name;
            RULE_SOURCES[existingIndex].enabled = true;
        } else {
            // 添加新的本地规则源
            RULE_SOURCES.push({
                name: name,
                url: "local://custom-rules",
                desc: "本地保存的自定义规则",
                isLocal: true,
                enabled: true
            });
        }
        
        // 保存到存储
        GM_setValue('customRuleSources', RULE_SOURCES);
        
        // 解析并应用规则
        parseRules(rules, name);
        
        // 更新过滤系统
        buildBloomFilter();
        optimizeMemoryUsage();
        
        return true;
    }

    function removeSubscription(url) {
        const initialLength = RULE_SOURCES.length;
        RULE_SOURCES = RULE_SOURCES.filter(source => source.url !== url);
        
        if (RULE_SOURCES.length !== initialLength) {
            // 保存到存储
            GM_setValue('customRuleSources', RULE_SOURCES);
            
            // 重新加载规则
            ruleDatabase = {
                networkFilters: new Map(),
                cosmeticFilters: new Map(),
                scriptlets: [],
                bloomFilter: new Set()
            };
            
            loadAllRules();
            return true;
        }
        
        return false;
    }

    function toggleSubscription(url, enabled) {
        const source = RULE_SOURCES.find(s => s.url === url);
        if (source) {
            source.enabled = enabled;
            GM_setValue('customRuleSources', RULE_SOURCES);
            
            // 重新加载规则
            ruleDatabase = {
                networkFilters: new Map(),
                cosmeticFilters: new Map(),
                scriptlets: [],
                bloomFilter: new Set()
            };
            
            loadAllRules();
            return true;
        }
        
        return false;
    }

    // ======================== 辅助函数 ========================
    function fakeResponse() {
        return new Response(null, {
            status: 404,
            statusText: 'Blocked by uBlock规则屏蔽器'
        });
    }

    function shouldDisable() {
        // 根据域名判断是否禁用
        const disabledDomains = GM_getValue('disabledDomains', []);
        return disabledDomains.includes(location.hostname);
    }

    // ======================== 用户界面扩展 ========================
    GM_registerMenuCommand("管理规则", () => {
        showRuleManager();
    });

    // 添加元素选择器入口
    GM_registerMenuCommand("选择元素屏蔽", () => {
        startElementPicker();
    });
    
    // 添加谷歌广告特定过滤命令
    GM_registerMenuCommand("强力拦截谷歌广告", () => {
        forceBlockGoogleAds();
    });
    
    // 显示规则管理器
    function showRuleManager() {
        // 检测是否是移动设备
        const isMobile = detectMobileDevice();
        
        // 创建管理器对话框
        const dialog = document.createElement('div');
        dialog.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: ${isMobile ? '95%' : '80%'};
            max-width: ${isMobile ? '100%' : '800px'};
            max-height: ${isMobile ? '90vh' : '80vh'};
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.2);
            z-index: 2147483647;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            font-family: Arial, sans-serif;
            font-size: ${isMobile ? '16px' : '14px'};
        `;
        
        // 对话框内容
        let dialogHTML = `
            <div style="padding: 15px; background: #f8f9fa; border-bottom: 1px solid #eee; display: flex; justify-content: space-between; align-items: center;">
                <h2 style="margin: 0; font-size: ${isMobile ? '20px' : '18px'}; color: #333;">uBlock规则管理器</h2>
                <button id="close-rule-dialog" style="background: none; border: none; cursor: pointer; font-size: ${isMobile ? '24px' : '20px'}; padding: ${isMobile ? '8px' : '0'};">×</button>
            </div>
            
            <div style="padding: 0 15px; overflow-y: auto; flex: 1;">`;
        
        // 添加移动端设备标识
        if (isMobile) {
            dialogHTML += `
                <div style="margin: 10px 0; padding: 8px; background: #e6f7ff; border-left: 4px solid #1890ff; border-radius: 4px;">
                    <p style="margin: 0; font-size: 14px;">已检测为移动设备，已自动启用移动端规则</p>
                </div>`;
        }
        
        dialogHTML += `
                <div style="margin: 15px 0;">
                    <h3 style="margin: 10px 0; font-size: ${isMobile ? '18px' : '16px'}; color: #444;">订阅规则源</h3>
                    <div id="rule-sources-container" style="max-height: ${isMobile ? '350px' : '250px'}; overflow-y: auto; border: 1px solid #eee; border-radius: 4px; padding: 10px;"></div>
                </div>
                
                <div style="margin: 15px 0; display: flex; flex-wrap: wrap; gap: 10px;">
                    <button id="add-subscription" style="padding: ${isMobile ? '10px 15px' : '8px 12px'}; background: #4285f4; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: ${isMobile ? '16px' : '14px'};">添加订阅</button>
                    <button id="clear-cache" style="padding: ${isMobile ? '10px 15px' : '8px 12px'}; background: #f1f3f4; color: #333; border: none; border-radius: 4px; cursor: pointer; font-size: ${isMobile ? '16px' : '14px'};">清除缓存</button>
                    <button id="import-export" style="padding: ${isMobile ? '10px 15px' : '8px 12px'}; background: #f1f3f4; color: #333; border: none; border-radius: 4px; cursor: pointer; font-size: ${isMobile ? '16px' : '14px'};">导入/导出规则</button>
                </div>
                
                <div style="margin: 15px 0; border-top: 1px solid #eee; padding-top: 15px;">
                    <h3 style="margin: 10px 0; font-size: ${isMobile ? '18px' : '16px'}; color: #444;">本地自定义规则</h3>
                    <textarea id="local-rules" style="width: 100%; height: ${isMobile ? '120px' : '150px'}; border: 1px solid #ddd; border-radius: 4px; padding: 10px; font-family: monospace; font-size: ${isMobile ? '14px' : '13px'}; resize: vertical;"></textarea>
                </div>
                
                <div style="margin: 15px 0;">
                    <button id="save-local-rules" style="padding: ${isMobile ? '10px 15px' : '8px 12px'}; background: #4285f4; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: ${isMobile ? '16px' : '14px'};">保存本地规则</button>
                </div>
                
                <div style="margin: 15px 0; border-top: 1px solid #eee; padding-top: 15px;">
                    <h3 style="margin: 10px 0; font-size: ${isMobile ? '18px' : '16px'}; color: #444;">设置</h3>
                    
                    <div style="margin: ${isMobile ? '15px' : '10px'} 0; display: flex; align-items: center;">
                        <label style="display: flex; align-items: center; cursor: pointer;">
                            <input type="checkbox" id="cache-enabled" style="margin-right: 8px; width: ${isMobile ? '20px' : 'auto'}; height: ${isMobile ? '20px' : 'auto'};"> 
                            <span>启用缓存（提高性能）</span>
                        </label>
                    </div>
                    
                    <div style="margin: ${isMobile ? '15px' : '10px'} 0; display: flex; align-items: center; flex-wrap: wrap;">
                        <label style="margin-right: 10px; ${isMobile ? 'margin-bottom: 5px; display: block; width: 100%;' : ''}">缓存更新间隔（分钟）：</label>
                        <input type="number" id="cache-interval" min="15" max="1440" style="width: ${isMobile ? '100px' : '80px'}; padding: ${isMobile ? '8px' : '5px'}; border: 1px solid #ddd; border-radius: 4px; font-size: ${isMobile ? '16px' : 'inherit'};">
                    </div>
                    
                    <div style="margin: ${isMobile ? '15px' : '10px'} 0; display: flex; align-items: center;">
                        <label style="display: flex; align-items: center; cursor: pointer;">
                            <input type="checkbox" id="popup-block-enabled" style="margin-right: 8px; width: ${isMobile ? '20px' : 'auto'}; height: ${isMobile ? '20px' : 'auto'};"> 
                            <span>启用弹窗拦截</span>
                        </label>
                    </div>
                </div>
            </div>
            
            <div style="padding: 15px; background: #f8f9fa; border-top: 1px solid #eee; text-align: right;">
                <button id="save-settings" style="padding: ${isMobile ? '12px 20px' : '8px 16px'}; background: #4285f4; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: ${isMobile ? '16px' : '14px'};">保存设置</button>
            </div>
        `;
        
        // 设置对话框内容
        dialog.innerHTML = dialogHTML;
        
        // 添加对话框到页面
        document.body.appendChild(dialog);
        
        // 获取对话框中的元素
        const closeButton = document.getElementById('close-rule-dialog');
        const addSubscriptionButton = document.getElementById('add-subscription');
        const clearCacheButton = document.getElementById('clear-cache');
        const localRulesTextarea = document.getElementById('local-rules');
        const saveLocalRulesButton = document.getElementById('save-local-rules');
        const cacheEnabledCheckbox = document.getElementById('cache-enabled');
        const cacheIntervalInput = document.getElementById('cache-interval');
        const popupBlockEnabledCheckbox = document.getElementById('popup-block-enabled');
        const saveSettingsButton = document.getElementById('save-settings');
        const ruleSourcesContainer = document.getElementById('rule-sources-container');
        const importExportButton = document.getElementById('import-export');
        
        // 加载当前规则源
        loadRuleSources();
        
        // 加载本地规则
        localRulesTextarea.value = GM_getValue('localCustomRules', '');
        
        // 加载设置
        cacheEnabledCheckbox.checked = CACHE_CONFIG.enabled;
        cacheIntervalInput.value = CACHE_CONFIG.updateInterval;
        popupBlockEnabledCheckbox.checked = POPUP_CONFIG.enabled;
        
        // 关闭对话框
        closeButton.addEventListener('click', function() {
            document.body.removeChild(dialog);
        });
        
        // 添加订阅
        addSubscriptionButton.addEventListener('click', function() {
            showAddSubscriptionDialog();
        });
        
        // 清除缓存
        clearCacheButton.addEventListener('click', function() {
            if (confirm('确定要清除所有缓存的规则吗？这将在下次刷新页面时重新下载所有规则。')) {
                clearCache();
                showNotification('缓存已清除，刷新页面后将重新下载规则');
            }
        });
        
        // 导入/导出规则
        importExportButton.addEventListener('click', function() {
            showImportExportDialog();
        });
        
        // 保存本地规则
        saveLocalRulesButton.addEventListener('click', function() {
            const rules = localRulesTextarea.value.trim();
            addLocalCustomRules(rules);
            showNotification('本地规则已保存并应用');
        });
        
        // 保存设置
        saveSettingsButton.addEventListener('click', function() {
            // 保存缓存设置
            CACHE_CONFIG.enabled = cacheEnabledCheckbox.checked;
            CACHE_CONFIG.updateInterval = parseInt(cacheIntervalInput.value) || 60;
            GM_setValue('cacheConfig', CACHE_CONFIG);
            
            // 保存弹窗拦截设置
            POPUP_CONFIG.enabled = popupBlockEnabledCheckbox.checked;
            GM_setValue('popupConfig', POPUP_CONFIG);
            
            showNotification('设置已保存，部分设置在刷新页面后生效');
            
            // 关闭对话框
            document.body.removeChild(dialog);
        });
        
        // 加载规则源列表
        function loadRuleSources() {
            ruleSourcesContainer.innerHTML = '';
            
            // 移动端样式优化
            const isMobile = detectMobileDevice();
            const itemMargin = isMobile ? '15px' : '10px';
            const itemPadding = isMobile ? '15px' : '10px';
            const itemFontSize = isMobile ? '15px' : '14px';
            const controlsGap = isMobile ? '15px' : '10px';
            const buttonFontSize = isMobile ? '14px' : '12px';
            const buttonPadding = isMobile ? '8px 12px' : '0';
            
            // 添加分类标题 - 移动端规则
            if (isMobile) {
                const mobileTitle = document.createElement('div');
                mobileTitle.style.cssText = `
                    padding: 8px 10px;
                    margin: 5px 0;
                    background: #f2f7ff;
                    border-radius: 4px;
                    font-weight: bold;
                    color: #1a73e8;
                `;
                mobileTitle.textContent = "移动端规则";
                ruleSourcesContainer.appendChild(mobileTitle);
                
                // 添加移动端规则源
                RULE_SOURCES.forEach((source, index) => {
                    if (source.name.includes("手机版") || source.name.includes("移动") || source.url.includes("mobile")) {
                        addRuleSourceItem(source, index, isMobile, itemMargin, itemPadding, itemFontSize, controlsGap, buttonFontSize, buttonPadding);
                    }
                });
                
                // 添加PC规则标题
                const pcTitle = document.createElement('div');
                pcTitle.style.cssText = `
                    padding: 8px 10px;
                    margin: 15px 0 5px 0;
                    background: #f2f7ff;
                    border-radius: 4px;
                    font-weight: bold;
                    color: #1a73e8;
                `;
                pcTitle.textContent = "通用规则";
                ruleSourcesContainer.appendChild(pcTitle);
                
                // 添加PC规则源
                RULE_SOURCES.forEach((source, index) => {
                    if (!source.name.includes("手机版") && !source.name.includes("移动") && !source.url.includes("mobile")) {
                        addRuleSourceItem(source, index, isMobile, itemMargin, itemPadding, itemFontSize, controlsGap, buttonFontSize, buttonPadding);
                    }
                });
            } else {
                // PC端显示全部规则
                RULE_SOURCES.forEach((source, index) => {
                    addRuleSourceItem(source, index, isMobile, itemMargin, itemPadding, itemFontSize, controlsGap, buttonFontSize, buttonPadding);
                });
            }
        }
        
        // 添加规则源项目
        function addRuleSourceItem(source, index, isMobile, itemMargin, itemPadding, itemFontSize, controlsGap, buttonFontSize, buttonPadding) {
            const sourceItem = document.createElement('div');
            sourceItem.style.cssText = `
                padding: ${itemPadding};
                margin-bottom: ${itemMargin};
                border-bottom: 1px solid #eee;
                ${isMobile ? 'display: block;' : 'display: flex; align-items: center; justify-content: space-between;'}
                ${isMobile ? 'font-size: '+itemFontSize+';' : ''}
                ${isMobile ? 'background-color: #fafafa; border-radius: 8px;' : ''}
            `;
            
            const sourceInfo = document.createElement('div');
            sourceInfo.style.cssText = `
                flex: 1;
                overflow: hidden;
                ${isMobile ? 'margin-bottom: 10px;' : ''}
            `;
            
            // 移动设备专用 - 添加规则类型标签
            if (isMobile) {
                let typeLabel = '';
                if (source.name.includes("手机版") || source.name.includes("移动") || source.url.includes("mobile")) {
                    typeLabel = `<span style="display: inline-block; font-size: 11px; padding: 2px 6px; background: #e6f7ff; color: #1890ff; border-radius: 4px; margin-left: 5px;">移动端</span>`;
                }
                
                sourceInfo.innerHTML = `
                    <div style="font-weight: bold; margin-bottom: 5px; color: #333; display: flex; align-items: center;">
                        ${source.name}${typeLabel}
                    </div>
                    <div style="font-size: 12px; color: #666; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-bottom: 3px;" title="${source.url}">URL: ${source.url}</div>
                    ${source.desc ? `<div style="font-size: 12px; color: #888;">${source.desc}</div>` : ''}
                `;
            } else {
                sourceInfo.innerHTML = `
                    <div style="font-weight: bold; margin-bottom: 3px; color: #333;">${source.name}</div>
                    <div style="font-size: 12px; color: #666; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" title="${source.url}">${source.url}</div>
                    ${source.desc ? `<div style="font-size: 12px; color: #888; margin-top: 3px;">${source.desc}</div>` : ''}
                `;
            }
            
            const sourceControls = document.createElement('div');
            sourceControls.style.cssText = `
                display: flex;
                align-items: center;
                ${isMobile ? 'justify-content: space-between;' : ''}
                gap: ${controlsGap};
            `;
            
            // 启用/禁用开关 - 滑动开关样式
            const toggleLabel = document.createElement('div');
            toggleLabel.style.cssText = `
                display: flex;
                align-items: center;
                cursor: pointer;
                ${isMobile ? 'flex: 1;' : ''}
            `;
            
            // 存储规则状态，使用let而不是const以便可以修改
            let currentEnabled = source.enabled !== false;
            
            // 创建开关轨道
            const switchTrack = document.createElement('div');
            switchTrack.style.cssText = `
                width: ${isMobile ? '50px' : '40px'};
                height: ${isMobile ? '24px' : '20px'};
                background: ${currentEnabled ? '#4285f4' : '#ccc'};
                border-radius: 12px;
                position: relative;
                transition: background 0.3s;
                margin-right: 8px;
            `;
            
            // 创建开关圆形滑块
            const switchKnob = document.createElement('div');
            switchKnob.style.cssText = `
                width: ${isMobile ? '20px' : '16px'};
                height: ${isMobile ? '20px' : '16px'};
                background: white;
                border-radius: 50%;
                position: absolute;
                top: 2px;
                left: ${currentEnabled ? (isMobile ? '26px' : '20px') : '4px'};
                transition: left 0.3s;
                box-shadow: 0 1px 3px rgba(0,0,0,0.2);
            `;
            
            // 添加滑块到轨道上
            switchTrack.appendChild(switchKnob);
            
            // 创建状态文本
            const toggleText = document.createElement('span');
            toggleText.textContent = currentEnabled ? '已启用' : '已禁用';
            toggleText.style.cssText = `
                font-size: ${isMobile ? '14px' : '12px'};
                color: ${currentEnabled ? '#4285f4' : '#666'};
                transition: color 0.3s;
            `;
            
            // 组合开关部件
            toggleLabel.appendChild(switchTrack);
            toggleLabel.appendChild(toggleText);
            
            // 点击事件处理
            toggleLabel.addEventListener('click', function() {
                // 切换状态并更新当前状态变量
                currentEnabled = !currentEnabled;
                
                // 更新视觉效果
                switchTrack.style.background = currentEnabled ? '#4285f4' : '#ccc';
                switchKnob.style.left = currentEnabled ? (isMobile ? '26px' : '20px') : '4px';
                toggleText.textContent = currentEnabled ? '已启用' : '已禁用';
                toggleText.style.color = currentEnabled ? '#4285f4' : '#666';
                
                // 执行切换功能
                toggleSubscription(source.url, currentEnabled);
                showNotification(`已${currentEnabled ? '启用' : '禁用'}规则源：${source.name}`);
            });
            
            // 控制按钮区
            const buttonContainer = document.createElement('div');
            buttonContainer.style.cssText = `
                display: flex;
                align-items: center;
                gap: 10px;
                ${isMobile ? 'flex: 1; justify-content: flex-end;' : ''}
            `;
            
            // 添加编辑按钮
            const editButton = document.createElement('button');
            editButton.textContent = '编辑';
            editButton.style.cssText = `
                background: ${isMobile ? '#f0f7ff' : 'none'};
                border: ${isMobile ? '1px solid #1a73e8' : 'none'};
                color: #1a73e8;
                cursor: pointer;
                font-size: ${buttonFontSize};
                padding: ${buttonPadding};
                ${isMobile ? 'border-radius: 4px;' : ''}
            `;
            
            // 禁止编辑默认规则源（前5个）
            if (index < 5) {
                editButton.disabled = true;
                editButton.style.opacity = '0.5';
                editButton.style.cursor = 'not-allowed';
            }
            
            editButton.addEventListener('click', function() {
                showEditSubscriptionDialog(source, index);
            });
            
            // 删除按钮
            const deleteButton = document.createElement('button');
            deleteButton.textContent = '删除';
            deleteButton.style.cssText = `
                background: ${isMobile ? '#fff0f0' : 'none'};
                border: ${isMobile ? '1px solid #d93025' : 'none'};
                color: #d93025;
                cursor: pointer;
                font-size: ${buttonFontSize};
                padding: ${buttonPadding};
                ${isMobile ? 'border-radius: 4px;' : ''}
            `;
            
            // 判断是否为可删除的规则
            // 只有"自定义屏蔽规则"和用户添加的自定义规则可以删除
            const isCustomRule = source.name === "自定义屏蔽规则" || 
                                source.name === "自定义屏蔽规则-手机版" || 
                                (source.url && !DEFAULT_RULE_SOURCES.some(defaultSource => defaultSource.url === source.url));
                                
            if (!isCustomRule || source.isLocal) {
                deleteButton.disabled = true;
                deleteButton.style.opacity = '0.5';
                deleteButton.style.cursor = 'not-allowed';
            }
            
            deleteButton.addEventListener('click', function() {
                if (confirm(`确定要删除规则源"${source.name}"吗？`)) {
                    removeSubscription(source.url);
                    loadRuleSources(); // 重新加载列表
                    showNotification(`已删除规则源：${source.name}`);
                }
            });
            
            buttonContainer.appendChild(editButton);
            buttonContainer.appendChild(deleteButton);
            
            sourceControls.appendChild(toggleLabel);
            sourceControls.appendChild(buttonContainer);
            
            sourceItem.appendChild(sourceInfo);
            
            // 在移动端，控制按钮单独一行显示
            if (isMobile) {
                sourceItem.appendChild(document.createElement('div')); // 分隔
                sourceItem.appendChild(sourceControls);
            } else {
                sourceItem.appendChild(sourceControls);
            }
            
            ruleSourcesContainer.appendChild(sourceItem);
        }
        
        // 添加订阅对话框
        function showAddSubscriptionDialog() {
            const isMobile = detectMobileDevice();
            const addDialog = document.createElement('div');
            addDialog.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                width: ${isMobile ? '90%' : '400px'};
                max-width: ${isMobile ? '100%' : '90%'};
                background: white;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.3);
                z-index: 2147483648;
                padding: ${isMobile ? '25px' : '20px'};
                font-family: Arial, sans-serif;
                font-size: ${isMobile ? '16px' : '14px'};
            `;
            
            addDialog.innerHTML = `
                <h3 style="margin-top: 0; font-size: ${isMobile ? '18px' : '16px'}; color: #333;">添加规则订阅</h3>
                
                <div style="margin: 15px 0;">
                    <label style="display: block; margin-bottom: 5px;">名称</label>
                    <input type="text" id="sub-name" placeholder="例如：自定义广告规则" style="width: 100%; padding: ${isMobile ? '10px' : '8px'}; box-sizing: border-box; border: 1px solid #ddd; border-radius: 4px; font-size: ${isMobile ? '16px' : 'inherit'};">
                </div>
                
                <div style="margin: 15px 0;">
                    <label style="display: block; margin-bottom: 5px;">URL</label>
                    <input type="text" id="sub-url" placeholder="https://example.com/rules.txt" style="width: 100%; padding: ${isMobile ? '10px' : '8px'}; box-sizing: border-box; border: 1px solid #ddd; border-radius: 4px; font-size: ${isMobile ? '16px' : 'inherit'};">
                </div>
                
                <div style="margin: 15px 0;">
                    <label style="display: block; margin-bottom: 5px;">描述（可选）</label>
                    <input type="text" id="sub-desc" placeholder="规则描述信息" style="width: 100%; padding: ${isMobile ? '10px' : '8px'}; box-sizing: border-box; border: 1px solid #ddd; border-radius: 4px; font-size: ${isMobile ? '16px' : 'inherit'};">
                </div>
                
                <div style="margin: 15px 0;">
                    <label style="display: flex; align-items: center; user-select: none; cursor: pointer;">
                        <input type="checkbox" id="is-mobile-rule" style="margin-right: 8px; ${isMobile ? 'width: 18px; height: 18px;' : ''}"> 
                        <span>这是移动端专用规则</span>
                    </label>
                </div>
                
                <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
                    <button id="cancel-add-sub" style="padding: ${isMobile ? '12px 20px' : '8px 16px'}; background: #f1f3f4; color: #333; border: none; border-radius: 4px; cursor: pointer; font-size: ${isMobile ? '16px' : 'inherit'};">取消</button>
                    <button id="confirm-add-sub" style="padding: ${isMobile ? '12px 20px' : '8px 16px'}; background: #4285f4; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: ${isMobile ? '16px' : 'inherit'};">添加</button>
                </div>
            `;
            
            document.body.appendChild(addDialog);
            
            // 设置移动端专用规则复选框状态
            if (isMobile) {
                document.getElementById('is-mobile-rule').checked = true;
            }
            
            // 取消按钮
            document.getElementById('cancel-add-sub').addEventListener('click', function() {
                document.body.removeChild(addDialog);
            });
            
            // 确认添加按钮
            document.getElementById('confirm-add-sub').addEventListener('click', function() {
                const name = document.getElementById('sub-name').value.trim();
                let url = document.getElementById('sub-url').value.trim();
                let desc = document.getElementById('sub-desc').value.trim();
                const isMobileRule = document.getElementById('is-mobile-rule').checked;
                
                if (!name || !url) {
                    alert('名称和URL不能为空！');
                    return;
                }
                
                if (!url.startsWith('http')) {
                    alert('URL格式不正确，必须以http://或https://开头');
                    return;
                }
                
                // 为移动端规则添加标记
                if (isMobileRule && !name.includes('移动') && !name.includes('手机')) {
                    name = name + '（移动端）';
                }
                
                if (isMobileRule && !desc) {
                    desc = '移动设备专用规则';
                }
                
                addCustomSubscription(name, url, desc);
                loadRuleSources(); // 重新加载列表
                document.body.removeChild(addDialog);
                showNotification(`已添加规则源：${name}`);
            });
        }
        
        // 编辑订阅对话框
        function showEditSubscriptionDialog(source, index) {
            const isMobile = detectMobileDevice();
            const editDialog = document.createElement('div');
            editDialog.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                width: ${isMobile ? '90%' : '400px'};
                max-width: ${isMobile ? '100%' : '90%'};
                background: white;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.3);
                z-index: 2147483648;
                padding: ${isMobile ? '25px' : '20px'};
                font-family: Arial, sans-serif;
                font-size: ${isMobile ? '16px' : '14px'};
            `;
            
            editDialog.innerHTML = `
                <h3 style="margin-top: 0; font-size: ${isMobile ? '18px' : '16px'}; color: #333;">编辑规则订阅</h3>
                
                <div style="margin: 15px 0;">
                    <label style="display: block; margin-bottom: 5px;">名称</label>
                    <input type="text" id="edit-sub-name" value="${source.name}" style="width: 100%; padding: ${isMobile ? '10px' : '8px'}; box-sizing: border-box; border: 1px solid #ddd; border-radius: 4px; font-size: ${isMobile ? '16px' : 'inherit'};">
                </div>
                
                <div style="margin: 15px 0;">
                    <label style="display: block; margin-bottom: 5px;">URL</label>
                    <input type="text" id="edit-sub-url" value="${source.url}" style="width: 100%; padding: ${isMobile ? '10px' : '8px'}; box-sizing: border-box; border: 1px solid #ddd; border-radius: 4px; font-size: ${isMobile ? '16px' : 'inherit'};">
                </div>
                
                <div style="margin: 15px 0;">
                    <label style="display: block; margin-bottom: 5px;">描述（可选）</label>
                    <input type="text" id="edit-sub-desc" value="${source.desc || ''}" style="width: 100%; padding: ${isMobile ? '10px' : '8px'}; box-sizing: border-box; border: 1px solid #ddd; border-radius: 4px; font-size: ${isMobile ? '16px' : 'inherit'};">
                </div>
                
                <div style="margin: 15px 0;">
                    <label style="display: flex; align-items: center; user-select: none; cursor: pointer;">
                        <input type="checkbox" id="edit-is-mobile-rule" style="margin-right: 8px; ${isMobile ? 'width: 18px; height: 18px;' : ''}"> 
                        <span>这是移动端专用规则</span>
                    </label>
                </div>
                
                <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
                    <button id="cancel-edit-sub" style="padding: ${isMobile ? '12px 20px' : '8px 16px'}; background: #f1f3f4; color: #333; border: none; border-radius: 4px; cursor: pointer; font-size: ${isMobile ? '16px' : 'inherit'};">取消</button>
                    <button id="confirm-edit-sub" style="padding: ${isMobile ? '12px 20px' : '8px 16px'}; background: #4285f4; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: ${isMobile ? '16px' : 'inherit'};">保存</button>
                </div>
            `;
            
            document.body.appendChild(editDialog);
            
            // 设置移动端专用规则复选框状态
            const isMobileRule = source.name.includes('移动') || source.name.includes('手机') || source.url.includes('mobile');
            document.getElementById('edit-is-mobile-rule').checked = isMobileRule;
            
            // 取消按钮
            document.getElementById('cancel-edit-sub').addEventListener('click', function() {
                document.body.removeChild(editDialog);
            });
            
            // 确认编辑按钮
            document.getElementById('confirm-edit-sub').addEventListener('click', function() {
                const name = document.getElementById('edit-sub-name').value.trim();
                let url = document.getElementById('edit-sub-url').value.trim();
                let desc = document.getElementById('edit-sub-desc').value.trim();
                const isMobileRule = document.getElementById('edit-is-mobile-rule').checked;
                
                if (!name || !url) {
                    alert('名称和URL不能为空！');
                    return;
                }
                
                if (!url.startsWith('http')) {
                    alert('URL格式不正确，必须以http://或https://开头');
                    return;
                }
                
                // 处理移动端规则标记
                let finalName = name;
                if (isMobileRule && !finalName.includes('移动') && !finalName.includes('手机')) {
                    finalName = finalName + '（移动端）';
                }
                
                if (isMobileRule && !desc) {
                    desc = '移动设备专用规则';
                }
                
                // 更新订阅信息
                const oldUrl = source.url;
                
                // 如果更改了URL，则需要删除旧订阅并添加新订阅
                if (url !== oldUrl) {
                    removeSubscription(oldUrl);
                    addCustomSubscription(finalName, url, desc);
                } else {
                    // 只更新名称和描述
                    RULE_SOURCES[index].name = finalName;
                    RULE_SOURCES[index].desc = desc;
                    GM_setValue('customRuleSources', RULE_SOURCES);
                }
                
                loadRuleSources(); // 重新加载列表
                document.body.removeChild(editDialog);
                showNotification(`已更新规则源：${finalName}`);
            });
        }
        
        // 导入/导出对话框
        function showImportExportDialog() {
            const isMobile = detectMobileDevice();
            const ieDialog = document.createElement('div');
            ieDialog.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                width: ${isMobile ? '90%' : '500px'};
                max-width: ${isMobile ? '100%' : '90%'};
                background: white;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0,0,0,0.3);
                z-index: 2147483648;
                padding: ${isMobile ? '25px' : '20px'};
                font-family: Arial, sans-serif;
                font-size: ${isMobile ? '16px' : '14px'};
            `;
            
            // 准备导出数据
            const exportData = {
                ruleSources: RULE_SOURCES,
                localRules: GM_getValue('localCustomRules', ''),
                cacheConfig: CACHE_CONFIG,
                popupConfig: POPUP_CONFIG
            };
            
            const exportText = JSON.stringify(exportData, null, 2);
            
            ieDialog.innerHTML = `
                <h3 style="margin-top: 0; font-size: ${isMobile ? '18px' : '16px'}; color: #333;">导入/导出规则</h3>
                
                <div style="margin: 15px 0;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
                        <label style="font-weight: bold;">规则数据</label>
                        <button id="copy-export" style="padding: ${isMobile ? '8px 12px' : '4px 8px'}; background: #f1f3f4; color: #333; border: none; border-radius: 4px; font-size: ${isMobile ? '14px' : '12px'}; cursor: pointer;">复制</button>
                    </div>
                    <textarea id="import-export-data" style="width: 100%; height: ${isMobile ? '150px' : '200px'}; padding: ${isMobile ? '10px' : '8px'}; box-sizing: border-box; border: 1px solid #ddd; border-radius: 4px; font-family: monospace; font-size: ${isMobile ? '14px' : '12px'};">${exportText}</textarea>
                </div>
                
                <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
                    <button id="cancel-import-export" style="padding: ${isMobile ? '12px 20px' : '8px 16px'}; background: #f1f3f4; color: #333; border: none; border-radius: 4px; cursor: pointer; font-size: ${isMobile ? '16px' : 'inherit'};">取消</button>
                    <button id="confirm-import" style="padding: ${isMobile ? '12px 20px' : '8px 16px'}; background: #4285f4; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: ${isMobile ? '16px' : 'inherit'};">导入</button>
                </div>
            `;
            
            document.body.appendChild(ieDialog);
            
            // 复制按钮
            document.getElementById('copy-export').addEventListener('click', function() {
                const textarea = document.getElementById('import-export-data');
                textarea.select();
                document.execCommand('copy');
                showNotification('已复制规则数据到剪贴板');
            });
            
            // 取消按钮
            document.getElementById('cancel-import-export').addEventListener('click', function() {
                document.body.removeChild(ieDialog);
            });
            
            // 导入按钮
            document.getElementById('confirm-import').addEventListener('click', function() {
                const importText = document.getElementById('import-export-data').value.trim();
                
                if (!importText) {
                    alert('导入数据不能为空！');
                    return;
                }
                
                try {
                    const importData = JSON.parse(importText);
                    
                    // 验证数据格式
                    if (!importData.ruleSources || !Array.isArray(importData.ruleSources)) {
                        throw new Error('无效的规则源数据');
                    }
                    
                    // 导入规则源
                    RULE_SOURCES = importData.ruleSources;
                    GM_setValue('customRuleSources', RULE_SOURCES);
                    
                    // 导入本地规则
                    if (importData.localRules) {
                        GM_setValue('localCustomRules', importData.localRules);
                        localRulesTextarea.value = importData.localRules;
                    }
                    
                    // 导入缓存配置
                    if (importData.cacheConfig) {
                        CACHE_CONFIG = importData.cacheConfig;
                        GM_setValue('cacheConfig', CACHE_CONFIG);
                        cacheEnabledCheckbox.checked = CACHE_CONFIG.enabled;
                        cacheIntervalInput.value = CACHE_CONFIG.updateInterval;
                    }
                    
                    // 导入弹窗配置
                    if (importData.popupConfig) {
                        POPUP_CONFIG = importData.popupConfig;
                        GM_setValue('popupConfig', POPUP_CONFIG);
                        popupBlockEnabledCheckbox.checked = POPUP_CONFIG.enabled;
                    }
                    
                    loadRuleSources(); // 重新加载列表
                    document.body.removeChild(ieDialog);
                    showNotification('已成功导入规则数据，部分设置在刷新页面后生效');
                } catch (error) {
                    alert(`导入失败：${error.message}\n\n请确保导入的是有效的JSON格式数据`);
                }
            });
        }
    }

    // 强力拦截谷歌广告
    function forceBlockGoogleAds() {
        // 强制移除Google广告脚本
        removeGoogleAdScripts();
        
        // 监听新添加的谷歌广告脚本
        observeGoogleAdScripts();
        
        // 强制移除常见的谷歌广告元素
        const adSelectors = [
            'ins.adsbygoogle',
            'div[id*="google_ads_iframe"]',
            'div[id*="div-gpt-ad"]',
            'div[data-ad-client]',
            'iframe[src*="googleads"]',
            'iframe[src*="doubleclick"]',
            'div.GoogleActiveViewElement',
            'div[data-google-query-id]',
            'div[class*="gpt-ad"]',
            'amp-ad[type="adsense"]',
            // 弹出广告或悬浮广告
            '.modal-ad',
            '.floating-ad',
            '.popup-ad',
            '.sticky-ad',
            '.overlay-ad',
            '.modal-dialog:has(a[href*="ads"])',
            '.modal-dialog:has(iframe[src*="ad"])',
            'div[style*="fixed"]:has(iframe[src*="ad"])',
            // 特定ID和类的广告容器
            '#ad-popup',
            '#ad-modal',
            '#ad-overlay',
            '.ad-popover',
            '.ad-interstitial',
            '.ad-notification'
        ];
        
        let removedCount = 0;
        
        adSelectors.forEach(selector => {
            try {
                const elements = document.querySelectorAll(selector);
                elements.forEach(el => {
                    if (el && el.parentNode) {
                        // 如果没找到或点击失败，直接移除元素
                        el.style.display = 'none';
                        removedCount++;
                    }
                });
            } catch (e) {
                // 忽略错误
            }
        });
        
        // 移除常见弹窗/模态窗广告
        const possibleAdContainers = document.querySelectorAll('.modal-dialog, .modal, .popup, [class*="modal"], [class*="popup"], [class*="dialog"]');
        possibleAdContainers.forEach(container => {
            if (isVisibleAdContainer(container)) {
                // 如果没有找到关闭按钮或点击失败，直接隐藏容器
                container.style.display = 'none';
                removedCount++;
            }
        });
        
        // 针对移动设备，处理全屏/半屏弹窗广告
        if (/Android|iPhone|iPad|iPod|Mobile/i.test(navigator.userAgent)) {
            // 查找位于页面顶层的元素
            const highZIndexElements = findHighZIndexElements();
            highZIndexElements.forEach(el => {
                el.style.display = 'none';
                removedCount++;
            });
        }
        
        if (removedCount > 0) {
            console.log(`[强力拦截] 已拦截 ${removedCount} 个广告元素`);
            showNotification(`已强力拦截 ${removedCount} 个广告元素`);
        } else {
            console.log('[强力拦截] 未发现广告元素');
            showNotification('未发现广告元素，或广告已被其他方式拦截');
        }
        
        return removedCount;
    }
    
    // 检查元素是否为可见的广告容器
    function isVisibleAdContainer(element) {
        if (!isElementVisible(element)) return false;
        
        // 检查大小，避免误判小元素
        const rect = element.getBoundingClientRect();
        if (rect.width < 100 || rect.height < 100) return false;
        
        // 检查是否包含广告相关内容
        const html = element.innerHTML.toLowerCase();
        const hasAdContent = html.includes('ad') || 
                          html.includes('广告') || 
                          html.includes('推广') || 
                          html.includes('赞助');
                          
        // 检查是否为模态窗口或弹出层
        const style = window.getComputedStyle(element);
        const isModal = style.position === 'fixed' || 
                      style.position === 'absolute' || 
                      style.zIndex > 1000;
                      
        return hasAdContent || isModal;
    }
    
    // 查找具有高z-index的元素（可能是弹窗广告）
    function findHighZIndexElements() {
        const allElements = document.querySelectorAll('div, section, aside');
        const highZElements = [];
        
        allElements.forEach(el => {
            try {
                const style = window.getComputedStyle(el);
                const zIndex = parseInt(style.zIndex);
                
                if (isElementVisible(el) && !isNaN(zIndex) && zIndex > 1000) {
                    // 检查尺寸，排除太小的元素
                    const rect = el.getBoundingClientRect();
                    if (rect.width > 150 && rect.height > 150) {
                        highZElements.push({
                            element: el,
                            zIndex: zIndex
                        });
                    }
                }
            } catch (e) {}
        });
        
        // 按z-index降序排序
        highZElements.sort((a, b) => b.zIndex - a.zIndex);
        
        // 返回前3个最高z-index的元素
        return highZElements.slice(0, 3).map(item => item.element);
    }

    // ======================== 元素选择器模块 ========================
    // 元素选择器状态
    let pickerActive = false;
    let highlightedElement = null;
    let pickerRoot = null;
    let pickerOverlay = null;
    
    // 启动元素选择器
    function startElementPicker() {
        // 如果已经激活，不重复启动
        if (pickerActive) return;
        
        pickerActive = true;
        showNotification('元素选择器已启动，点击要屏蔽的元素');
        
        // 创建透明覆盖层以捕获所有元素包括高层级广告
        pickerOverlay = document.createElement('div');
        pickerOverlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: transparent;
            z-index: 2147483647; /* 最高层级 */
            cursor: crosshair;
        `;
        document.body.appendChild(pickerOverlay);
        
        // 创建选择器UI
        createPickerUI();
        
        // 设置事件处理
        pickerOverlay.addEventListener('mousemove', onPickerMouseMove);
        pickerOverlay.addEventListener('click', onPickerClick);
        
        // 右键退出
        pickerOverlay.addEventListener('contextmenu', function(e) {
            e.preventDefault();
            stopElementPicker();
            return false;
        });
        
        // ESC键退出
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && pickerActive) {
                stopElementPicker();
            }
        });
    }
    
    // 创建选择器UI
    function createPickerUI() {
        // 创建选择器UI容器
        pickerRoot = document.createElement('div');
        pickerRoot.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            z-index: 2147483647;
            padding: 5px 10px;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            font-family: Arial, sans-serif;
            font-size: 12px;
            border-radius: 0 0 4px 0;
            pointer-events: none;
        `;
        
        // 设置UI内容
        pickerRoot.innerHTML = `
            <div style="margin: 5px 0;">
                <p style="margin: 0 0 5px 0;">正在选择元素，点击要屏蔽的元素</p>
                <p style="margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 300px;" id="ublock-selected-element">鼠标悬停在元素上显示选择器</p>
            </div>
            <div style="margin: 5px 0; font-size: 10px;">
                <p style="margin: 0;">按ESC键或右键点击取消</p>
            </div>
        `;
        
        document.body.appendChild(pickerRoot);
    }
    
    // 处理选择器鼠标移动
    function onPickerMouseMove(event) {
        if (!pickerActive) return;
        
        // 获取鼠标下方元素，忽略覆盖层和UI自身
        const x = event.clientX;
        const y = event.clientY;
        pickerOverlay.style.pointerEvents = 'none';
        const element = document.elementFromPoint(x, y);
        pickerOverlay.style.pointerEvents = 'auto';
        
        // 忽略选择器UI
        if (element && element !== pickerOverlay && !pickerRoot.contains(element)) {
            highlightElement(element);
        }
    }
    
    // 处理选择器点击事件
    function onPickerClick(event) {
        if (!pickerActive) return;
        
        event.preventDefault();
        event.stopPropagation();
        
        // 获取点击位置元素
        const x = event.clientX;
        const y = event.clientY;
        pickerOverlay.style.pointerEvents = 'none';
        const element = document.elementFromPoint(x, y);
        pickerOverlay.style.pointerEvents = 'auto';
        
        if (element && element !== pickerOverlay && !pickerRoot.contains(element)) {
            confirmElementBlock(element);
            stopElementPicker();
        }
        
        return false;
    }
    
    // 停止元素选择器
    function stopElementPicker() {
        // 移除高亮
        if (highlightedElement) {
            highlightedElement.style.outline = '';
            highlightedElement = null;
        }
        
        // 移除选择器UI
        if (pickerRoot) {
            document.body.removeChild(pickerRoot);
            pickerRoot = null;
        }
        
        // 移除覆盖层
        if (pickerOverlay) {
            // 移除事件监听
            pickerOverlay.removeEventListener('mousemove', onPickerMouseMove);
            pickerOverlay.removeEventListener('click', onPickerClick);
            
            document.body.removeChild(pickerOverlay);
            pickerOverlay = null;
        }
        
        // 重置状态
        pickerActive = false;
    }
    
    // 高亮元素
    function highlightElement(element) {
        // 移除之前的高亮
        if (highlightedElement) {
            highlightedElement.style.outline = '';
        }
        
        // 高亮新元素
        highlightedElement = element;
        highlightedElement.style.outline = '2px solid #f00';
        
        // 更新UI显示
        updatePickerUI(element);
    }
    
    // 更新选择器UI
    function updatePickerUI(element) {
        if (!pickerRoot) return;
        
        const selector = generateSelector(element);
        const elementInfo = document.getElementById('ublock-selected-element');
        
        if (elementInfo) {
            elementInfo.textContent = selector;
        }
    }
    
    // 生成CSS选择器 - 增强版，更好地处理广告元素
    function generateSelector(element) {
        if (!element || element === document.body || element === document.documentElement) {
            return 'body';
        }

        // 检查是否是广告弹窗类元素
        const isPopupAd = isAdPopup(element);
        if (isPopupAd) {
            return isPopupAd; // 返回特殊处理的选择器
        }
        
        // 1. 尝试使用ID
        if (element.id) {
            const idSelector = `#${element.id}`;
            // 确认这个ID是唯一的
            if (document.querySelectorAll(idSelector).length === 1) {
                return idSelector;
            }
        }
        
        // 2. 尝试使用类名组合
        if (element.className && typeof element.className === 'string') {
            const classes = element.className.trim().split(/\s+/);
            if (classes.length > 0 && classes[0]) {
                // 先尝试使用所有类名
                if (classes.length > 1) {
                    const classSelector = `.${classes.join('.')}`;
                    // 检查是否唯一
                    if (document.querySelectorAll(classSelector).length === 1) {
                        return classSelector;
                    }
                }
                
                // 然后尝试使用单个类名（从最有特征性的开始）
                for (const cls of classes) {
                    // 广告相关的类名优先使用
                    if (/ad|banner|popup|modal|dialog|overlay/i.test(cls)) {
                        const singleClassSelector = `.${cls}`;
                        if (document.querySelectorAll(singleClassSelector).length < 5) {
                            return singleClassSelector;
                        }
                    }
                }
                
                // 最后尝试第一个类名
                const singleClassSelector = `.${classes[0]}`;
                if (document.querySelectorAll(singleClassSelector).length < 3) {
                    return singleClassSelector;
                }
            }
        }
        
        // 3. 尝试使用标签+文本内容（针对广告文字）
        const tagName = element.tagName.toLowerCase();
        const text = element.textContent ? element.textContent.trim() : '';
        if (text && /广告|赞助|推广|ad|sponsor|advertisement/i.test(text)) {
            // 使用:has选择器或:contains选择器
            return `${tagName}:has-text(${text.substring(0, 10)})`;
        }
        
        // 4. 尝试使用HTML结构特征
        if (hasAdAttributes(element)) {
            let attributeSelector = tagName;
            
            // 添加常见的广告特征属性
            const adAttributes = hasAdAttributes(element);
            for (const attr in adAttributes) {
                if (adAttributes[attr]) {
                    attributeSelector += `[${attr}="${adAttributes[attr]}"]`;
                }
            }
            
            return attributeSelector;
        }
        
        // 5. 如果有高z-index或fixed/absolute定位，可能是广告
        const computedStyle = window.getComputedStyle(element);
        const position = computedStyle.position;
        const zIndex = parseInt(computedStyle.zIndex);
        
        if ((position === 'fixed' || position === 'absolute') && zIndex > 1000) {
            return `${tagName}[style*="position: ${position}"]`;
        }
        
        // 6. 如果父元素有ID，使用它作为基础
        const parent = element.parentElement;
        if (parent && parent.id && parent !== document.body) {
            return `#${parent.id} > ${tagName}`;
        }
        
        // 7. 最后，创建更精确的路径选择器
        return createPathSelector(element);
    }
    
    // 检查元素是否有广告特征属性
    function hasAdAttributes(element) {
        const adAttributeMap = {};
        const attributes = [
            'data-ad', 'data-ad-client', 'data-ad-slot', 'data-adtest', 'data-ad-unit',
            'data-adblock', 'data-adbox', 'data-advertisement', 'aria-label', 'role'
        ];
        
        for (const attr of attributes) {
            if (element.hasAttribute(attr)) {
                adAttributeMap[attr] = element.getAttribute(attr);
            }
        }
        
        return Object.keys(adAttributeMap).length > 0 ? adAttributeMap : false;
    }
    
    // 检查元素是否是广告弹窗
    function isAdPopup(element) {
        // 检查元素及其祖先元素
        let current = element;
        let level = 0;
        
        while (current && level < 3) {
            // 检查元素内容是否包含广告标记
            if (current.textContent && /^广告$|^AD$|^\s*广告\s*$/.test(current.textContent.trim())) {
                return `*:has(${current.tagName.toLowerCase()}:contains(广告))`;
            }
            
            // 检查样式特征是否是弹窗
            const style = window.getComputedStyle(current);
            if (
                (style.position === 'fixed' || style.position === 'absolute') &&
                parseInt(style.zIndex) > 1000 &&
                current.offsetWidth > 100 && current.offsetHeight > 100
            ) {
                // 查找元素内是否有关闭按钮
                const closeButtons = current.querySelectorAll('button, [role="button"], [aria-label*="关闭"], [aria-label*="close"]');
                if (closeButtons.length > 0) {
                    return `${current.tagName.toLowerCase()}[style*="position: ${style.position}"]`;
                }
            }
            
            // 检查类名和ID是否包含广告标记
            if (current.className && /ad|popup|modal|dialog/i.test(current.className)) {
                return `.${current.className.split(' ')[0]}`;
            }
            
            if (current.id && /ad|popup|modal|dialog/i.test(current.id)) {
                return `#${current.id}`;
            }
            
            // 特定广告案例 - Snipaste广告
            if (current.textContent && /Snipaste|截图/.test(current.textContent)) {
                return `${current.tagName.toLowerCase()}:has-text(Snipaste)`;
            }
            
            current = current.parentElement;
            level++;
        }
        
        return false;
    }
    
    // 确认屏蔽元素
    function confirmElementBlock(element) {
        if (!element) return;
        
        // 检查是否是广告类型元素
        const isAd = isAdPopup(element) || element.textContent?.includes('广告');
        
        // 生成基本选择器
        const selector = generateSelector(element);
        const hostname = location.hostname;
        
        // 创建规则
        const newRule = `${hostname}##${selector}`;
        
        // 显示规则导出对话框
        showRuleExportDialog(newRule, element, isAd);
    }
    
    // 显示规则导出对话框
    function showRuleExportDialog(rule, element, isAd = false) {
        // 创建对话框
        const dialog = document.createElement('div');
        dialog.style.cssText = `
            position: fixed;
            top: 30%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            border: 1px solid #ccc;
            border-radius: 8px;
            padding: 20px;
            z-index: 2147483647;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            width: 400px;
            max-width: 90%;
            font-family: Arial, sans-serif;
        `;
        
        // 获取广告专用规则（如果适用）
        let adSpecificRule = '';
        if (isAd) {
            // 创建更广泛的规则，可以捕获更多类似广告
            const tagName = element.tagName.toLowerCase();
            const computedStyle = window.getComputedStyle(element);
            
            if (computedStyle.position === 'fixed' || computedStyle.position === 'absolute') {
                adSpecificRule = `${hostname}##${tagName}[style*="position: ${computedStyle.position}"]`;
            } else if (element.className && /ad|popup|modal/i.test(element.className)) {
                adSpecificRule = `${hostname}##[class*="${element.className.split(' ')[0]}"]`;
            } else {
                adSpecificRule = `${hostname}##div:has-text(广告):not(script)`;
            }
        }
        
        // 设置对话框内容
        dialog.innerHTML = `
            <h3 style="margin-top: 0; color: #333; font-size: 16px;">元素屏蔽规则</h3>
            ${isAd ? `
            <div style="margin: 10px 0; padding: 8px; background: #FFF3CD; border-left: 4px solid #FFE69C; color: #856404;">
                <p style="margin: 0; font-size: 13px;">✓ 检测到广告元素，已生成专用规则</p>
            </div>
            ` : ''}
            <div style="margin: 10px 0;">
                <label style="display: block; margin-bottom: 5px; font-weight: bold; font-size: 13px;">选择规则类型：</label>
                <select id="rule-type-selector" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; background: #f9f9f9;">
                    <option value="standard" selected>标准规则</option>
                    ${isAd ? `<option value="adSpecific">广告专用规则</option>` : ''}
                    <option value="custom">自定义规则</option>
                </select>
            </div>
            <div style="margin: 10px 0;">
                <textarea id="rule-text" style="width: 100%; height: 80px; padding: 8px; box-sizing: border-box; border: 1px solid #ddd; border-radius: 4px; font-family: monospace;">${rule}</textarea>
            </div>
            <div style="margin: 15px 0;">
                <label style="display: flex; align-items: center; user-select: none; cursor: pointer;">
                    <input type="checkbox" id="preview-effect" checked style="margin-right: 8px;"> 
                    <span>预览效果（暂时隐藏元素）</span>
                </label>
            </div>
            <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 15px;">
                <button id="copy-rule" style="padding: 8px 12px; border: none; background: #f0f0f0; border-radius: 4px; cursor: pointer;">复制规则</button>
                <button id="save-rule" style="padding: 8px 12px; border: none; background: #4285f4; color: white; border-radius: 4px; cursor: pointer;">保存到本地规则</button>
                <button id="close-dialog" style="padding: 8px 12px; border: none; background: #f0f0f0; border-radius: 4px; cursor: pointer;">关闭</button>
            </div>
        `;
        
        // 添加对话框到页面
        document.body.appendChild(dialog);
        
        // 获取对话框中的元素
        const ruleTypeSelector = document.getElementById('rule-type-selector');
        const ruleTextarea = document.getElementById('rule-text');
        const previewCheckbox = document.getElementById('preview-effect');
        const copyButton = document.getElementById('copy-rule');
        const saveButton = document.getElementById('save-rule');
        const closeButton = document.getElementById('close-dialog');
        
        // 规则类型选择变化
        ruleTypeSelector.addEventListener('change', function() {
            if (this.value === 'standard') {
                ruleTextarea.value = rule;
            } else if (this.value === 'adSpecific' && adSpecificRule) {
                ruleTextarea.value = adSpecificRule;
            } else if (this.value === 'custom') {
                // 保持当前文本，允许用户自定义
            }
        });
        
        // 设置预览效果
        let originalDisplay = element.style.display;
        element.style.display = 'none'; // 默认预览（隐藏元素）
        
        previewCheckbox.addEventListener('change', function() {
            element.style.display = this.checked ? 'none' : originalDisplay;
        });
        
        // 复制规则
        copyButton.addEventListener('click', function() {
            ruleTextarea.select();
            document.execCommand('copy');
            showNotification('规则已复制到剪贴板');
        });
        
        // 保存规则
        saveButton.addEventListener('click', function() {
            const ruleToSave = ruleTextarea.value.trim();
            
            // 获取本地自定义规则
            let localRules = GM_getValue('localCustomRules', '');
            
            // 检查规则是否已存在
            if (localRules.includes(ruleToSave)) {
                showNotification('规则已存在于本地规则中');
            } else {
                // 添加规则并保存
                if (localRules && !localRules.endsWith('\n')) {
                    localRules += '\n';
                }
                localRules += ruleToSave;
                GM_setValue('localCustomRules', localRules);
                
                // 立即应用规则
                const [domain, sel] = ruleToSave.split('##');
                if (sel) {
                    addCosmeticRule(domain, { selector: sel, source: '本地自定义规则' });
                    // 确保元素保持隐藏
                    element.style.display = 'none';
                }
                
                showNotification('规则已保存到本地规则并立即应用');
            }
            
            // 关闭对话框
            closeDialog();
        });
        
        // 关闭对话框
        closeButton.addEventListener('click', closeDialog);
        
        // 关闭对话框函数
        function closeDialog() {
            document.body.removeChild(dialog);
            if (!previewCheckbox.checked) {
                element.style.display = originalDisplay;
            }
        }
        
        // 点击其他区域不关闭对话框
        dialog.addEventListener('click', function(event) {
            event.stopPropagation();
        });
    }
    
    // 显示通知
    function showNotification(message) {
        const isMobile = detectMobileDevice();
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            bottom: ${isMobile ? '30px' : '20px'};
            left: ${isMobile ? '50%' : '20px'};
            ${isMobile ? 'transform: translateX(-50%);' : ''}
            background: #333;
            color: #fff;
            padding: ${isMobile ? '12px 20px' : '10px 20px'};
            border-radius: 4px;
            z-index: 2147483647;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            font-family: Arial, sans-serif;
            font-size: ${isMobile ? '16px' : '14px'};
            max-width: ${isMobile ? '90%' : '80%'};
            text-align: center;
            word-break: break-all;
        `;
        notification.textContent = message;
        document.body.appendChild(notification);
        
        // 3秒后自动移除
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 3000);
    }

    // 创建基于路径的选择器
    function createPathSelector(element) {
        let selector = element.tagName.toLowerCase();
        let current = element;
        let path = [];
        
        // 向上最多4层
        for (let i = 0; i < 4; i++) {
            const parent = current.parentElement;
            if (!parent || parent === document.body || parent === document.documentElement) {
                break;
            }
            
            if (parent.id) {
                path.unshift(`#${parent.id}`);
                break;
            } else if (parent.className && typeof parent.className === 'string') {
                const classes = parent.className.trim().split(/\s+/);
                if (classes.length > 0 && classes[0]) {
                    path.unshift(`.${classes[0]}`);
                    break;
                }
            } else {
                const siblings = Array.from(parent.children).filter(c => c.tagName === current.tagName);
                if (siblings.length > 1) {
                    const index = siblings.indexOf(current) + 1;
                    path.unshift(`${parent.tagName.toLowerCase()} > ${current.tagName.toLowerCase()}:nth-of-type(${index})`);
                } else {
                    path.unshift(parent.tagName.toLowerCase());
                }
            }
            
            current = parent;
        }
        
        // 如果没有构建路径，使用标签和位置
        if (path.length === 0) {
            const index = Array.from(element.parentElement.children).indexOf(element) + 1;
            return `${element.tagName.toLowerCase()}:nth-child(${index})`;
        }
        
        return path.join(' > ') + (path.length ? ' > ' : '') + selector;
    }

    // 特殊处理谷歌广告
    function applyGoogleAdsFiltering() {
        // 获取所有谷歌广告相关的元素
        const adsElements = document.querySelectorAll('ins.adsbygoogle, div[id*="google_ads"], div[data-ad-client], iframe[src*="googleads"], iframe[src*="doubleclick"]');
        if (adsElements.length === 0) return;
        
        console.log(`[谷歌广告过滤] 发现 ${adsElements.length} 个谷歌广告元素`);
        
        // 尝试移除广告元素
        adsElements.forEach(element => {
            if (element.parentNode) {
                element.style.display = 'none';
                // 可选：完全移除元素
                // element.parentNode.removeChild(element);
            }
        });
        
        // 禁用谷歌广告相关的JavaScript对象
        if (window.google && window.google.ads) {
            try {
                window.google.ads = {};
                console.log('[谷歌广告过滤] 已禁用google.ads对象');
            } catch (e) {}
        }
    }
    
    // 移除谷歌广告脚本
    function removeGoogleAdScripts() {
        const adScripts = document.querySelectorAll('script[src*="adsbygoogle"], script[src*="pagead2"], script[src*="googleads"], script[src*="doubleclick"]');
        let removedCount = 0;
        
        adScripts.forEach(script => {
            if (script && script.parentNode) {
                script.parentNode.removeChild(script);
                removedCount++;
            }
        });
        
        // 阻止adsbygoogle对象
        if (window.adsbygoogle) {
            try {
                window.adsbygoogle = undefined;
                delete window.adsbygoogle;
                
                // 重新定义为空对象，并拦截任何属性访问
                Object.defineProperty(window, 'adsbygoogle', {
                    value: {},
                    writable: false,
                    configurable: false
                });
                
                console.log('[广告拦截] adsbygoogle 对象已禁用');
            } catch (e) {
                console.debug('[广告拦截] 无法完全禁用 adsbygoogle:', e);
            }
        }
        
        return removedCount;
    }
    
    // 监听新添加的谷歌广告脚本
    function observeGoogleAdScripts() {
        if (!window.MutationObserver) return;
        
        // 避免重复创建观察器
        if (window._adScriptObserver) return;
        
        const observer = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
                if (mutation.type === 'childList') {
                    mutation.addedNodes.forEach(node => {
                        if (node.nodeName === 'SCRIPT' && node.src && 
                            (node.src.includes('adsbygoogle') || 
                             node.src.includes('pagead2') || 
                             node.src.includes('googleads') || 
                             node.src.includes('doubleclick'))) {
                            
                            node.parentNode.removeChild(node);
                            console.log(`[谷歌广告] 阻止加载广告脚本: ${node.src}`);
                        }
                    });
                }
            });
        });
        
        observer.observe(document.documentElement, {
            childList: true,
            subtree: true
        });
        
        // 保存观察器引用
        window._adScriptObserver = observer;
    }

    // 检查元素是否可见
    function isElementVisible(element) {
        if (!element) return false;
        
        const style = window.getComputedStyle(element);
        return style.display !== 'none' && 
               style.visibility !== 'hidden' && 
               style.opacity !== '0' &&
               element.offsetWidth > 0 && 
               element.offsetHeight > 0;
    }
    
    // 查找广告容器元素
    function findParentAdContainer(element) {
        let current = element;
        const maxDepth = 5; // 最多向上查找5层
        
        for (let i = 0; i < maxDepth; i++) {
            current = current.parentElement;
            if (!current) break;
            
            // 检查是否是广告容器
            if (
                current.classList && (
                    current.classList.contains('ad-container') ||
                    current.classList.contains('adsbygoogle') ||
                    current.classList.contains('ad-unit') ||
                    current.classList.contains('GoogleActiveViewElement')
                ) ||
                current.id && (
                    current.id.includes('ad-') ||
                    current.id.includes('gpt-ad') ||
                    current.id.includes('google_ads')
                ) ||
                current.hasAttribute('data-ad-client') ||
                current.hasAttribute('data-google-query-id') ||
                // 查找大尺寸容器
                (current.offsetWidth > 300 && current.offsetHeight > 200 &&
                 (current.id?.toLowerCase().includes('ad') || 
                  current.className?.toLowerCase().includes('ad')))
            ) {
                return current;
            }
        }
        
        return null;
    }

    // 网络拦截初始化
    function initializeNetworkInterception() {
        // 拦截fetch
        const nativeFetch = window.fetch;
        window.fetch = function(input) {
            // 先使用简单的URL检查避免额外开销
            const url = input instanceof Request ? input.url : input;
            return nativeFetch.apply(this, arguments);
        };
        
        // 拦截XMLHttpRequest
        const nativeOpen = XMLHttpRequest.prototype.open;
        XMLHttpRequest.prototype.open = function(method, url) {
            nativeOpen.apply(this, arguments);
        };
    }
    
    // 添加样式容器
    function addStyleContainer() {
        if (!document.getElementById('ublock-cosmetic-filters')) {
            const styleEl = document.createElement('style');
            styleEl.id = 'ublock-cosmetic-filters';
            document.head.appendChild(styleEl);
        }
    }
})();